#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import re
import os
import sys
import time

def update_android_config(tunnel_url):
    """更新Android配置为Cloudflare Tunnel地址"""
    print(f"📱 更新Android配置: {tunnel_url}")
    
    # 确保URL格式正确
    if not tunnel_url.startswith(('http://', 'https://')):
        tunnel_url = f"https://{tunnel_url}"
    
    # 转换为WebSocket URL
    ws_url = tunnel_url.replace('https://', 'wss://').replace('http://', 'ws://')
    
    # 更新WebSocketManager.kt
    websocket_file = "app/src/main/java/com/example/myapplication/realtime/WebSocketManager.kt"
    
    if not os.path.exists(websocket_file):
        print("❌ WebSocketManager.kt 文件不存在")
        return False
    
    try:
        with open(websocket_file, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # 备份
        backup_file = f"{websocket_file}.backup_{int(time.time())}"
        with open(backup_file, 'w', encoding='utf-8') as f:
            f.write(content)
        
        # 更新PUBLIC_SERVER_URL
        pattern = r'private const val PUBLIC_SERVER_URL = "ws[s]?://[^"]*"'
        replacement = f'private const val PUBLIC_SERVER_URL = "{ws_url}"'
        
        if 'PUBLIC_SERVER_URL' in content:
            content = re.sub(pattern, replacement, content)
        else:
            # 添加新的URL配置
            insert_point = content.find('class WebSocketManager')
            if insert_point != -1:
                insert_point = content.find('{', insert_point) + 1
                content = content[:insert_point] + f'\n    private const val PUBLIC_SERVER_URL = "{ws_url}"' + content[insert_point:]
        
        with open(websocket_file, 'w', encoding='utf-8') as f:
            f.write(content)
        
        print(f"✅ Android配置已更新")
        print(f"🔗 WebSocket地址: {ws_url}")
        print(f"💾 备份文件: {backup_file}")
        
        return True
        
    except Exception as e:
        print(f"❌ 配置更新失败: {e}")
        return False

if __name__ == "__main__":
    if len(sys.argv) != 2:
        tunnel_url = input("请输入Cloudflare Tunnel地址: ")
    else:
        tunnel_url = sys.argv[1]
    
    if update_android_config(tunnel_url):
        print("\n✅ 配置更新完成!")
        print("\n📝 下一步:")
        print("1. 编译APK: gradlew assembleRelease")
        print("2. 安装APK: adb install -r app/build/outputs/apk/release/app-release.apk")
    else:
        print("\n❌ 配置更新失败")
